package com.qianxun.watchdog.communication;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class CommunicationAcceptor {

    private MessageProcessor messageProcessor ;

    private Callback callback;

    private int port;

    public CommunicationAcceptor(int port ,MessageHandler messageHandler ,Callback overCallback){
        this.messageProcessor = new MessageProcessor(messageHandler);
        this.port = port;
        this.callback = overCallback;
    }

    public void accept() throws IOException {
        ServerSocket serverSocket = new ServerSocket(this.port);
        new Thread(()->{
            Socket socket = null;
            try {
                while ((socket = serverSocket.accept()) != null) {
                    this.messageProcessor.addMessageSocket(socket);
                }
            }catch (Exception e){}
            this.messageProcessor.shutdown();
            System.out.println("CommunicationAcceptor stoped");
            this.callback.call();
        }).start();
    }

    public int getPort(){
        return this.port;
    }
}
